const httpStatus = require('http-status');
const adminService = require('./admin.service');
const ApiError = require('../utils/ApiError');
const tokenService = require('./token.service');

/**
 * 管理员登录
 * @param {string} username - 用户名
 * @param {string} password - 密码
 * @returns {Promise<Admin>}
 */
const loginAdmin = async (username, password) => {
  const admin = await adminService.getAdminByUsername(username);
  // --- DEBUG LOGGING START ---
  console.log('[AuthService] Admin found in DB for username ', username, ':', admin ? admin.toObject({ getters: true }) : null);
  // --- DEBUG LOGGING END ---

  if (!admin) {
    // --- DEBUG LOGGING START ---
    console.log('[AuthService] Admin not found for username:', username);
    // --- DEBUG LOGGING END ---
    throw new ApiError(httpStatus.UNAUTHORIZED, '用户名或密码不正确');
  }

  // --- DEBUG LOGGING START ---
  // 注意：不要在生产环境中记录明文密码或完整的哈希密码细节，这里仅为调试
  console.log(`[AuthService] Attempting to match password for admin: ${username}`);
  // --- DEBUG LOGGING END ---
  const isMatch = await admin.isPasswordMatch(password);
  // --- DEBUG LOGGING START ---
  console.log('[AuthService] Password match result for admin ', username, ':', isMatch);
  // --- DEBUG LOGGING END ---

  if (!isMatch) {
    // --- DEBUG LOGGING START ---
    console.log('[AuthService] Password mismatch for admin:', username);
    // --- DEBUG LOGGING END ---
    throw new ApiError(httpStatus.UNAUTHORIZED, '用户名或密码不正确');
  }

  if (!admin.isActive) {
    throw new ApiError(httpStatus.FORBIDDEN, '管理员账号已被禁用');
  }
  return admin;
};

/**
 * 生成管理员登录令牌
 * @param {object} admin - 管理员对象
 * @returns {Promise<Object>} - 包含access和refresh token的对象
 */
const generateAdminToken = async (admin) => {
  // 使用统一的token生成函数，指定用户类型为'admin'
  const tokens = await tokenService.generateAuthTokens(admin, 'admin');
  return tokens;
};

module.exports = {
  loginAdmin,
  generateAdminToken,
}; 